<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>取消请求</title>
    <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.min.js"></script>

</head>

<body>
    <button>发送</button>
    <button>取消</button>
    <script>
        // xhr 如何取消请求
        // let xhr;
        // let btns = document.querySelectorAll('button');
        // btns[0].onclick =function(){
        //     xhr = new XMLHttpRequest();
        //     xhr.open('get','http://localhost:8080/timeout');
        //     xhr.send();
        //     xhr.onreadystatechange = function(){
        //         if(xhr.readyState === 4){
        //             if(xhr.status >=200 && xhr.status < 300){
        //                 console.log(xhr.response);
        //             }
        //         }
        //     }
        // }
        // btns[1].onclick = function(){
        //     xhr.abort();
        // }


        let cancel = null;
        let btns = document.querySelectorAll('button');
        btns[0].onclick =function(){
            axios({
                method:'get',
                url: 'http://localhost:8080/timeout',
                //增加一个配置属性， cancelToken
                cancelToken: new axios.CancelToken(c=>{
                    cancel = c;
                })
            })
        }
        btns[1].onclick = function(){
            cancel();
        }

    </script>
</body>

</html>